import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
  Plus,
  Trash2,
  Edit2,
  Send,
  Download,
  Upload,
  Mail,
  Check,
  AlertCircle,
  Loader2,
  RefreshCw,
} from 'lucide-react';
import { emailAccountsAPI, type EmailAccount } from '@/lib/apiClient';

/**
 * 邮箱账号管理页面
 * 支持添加、编辑、删除邮箱配置，测试连接和拉取邮件
 */
export default function EmailAccounts() {
  const [accounts, setAccounts] = useState<EmailAccount[]>([]);
  const [isAdding, setIsAdding] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    smtp_server: '',
    smtp_port: 587,
    imap_server: '',
    imap_port: 993,
    username: '',
    password: '',
    use_ssl: true,
    is_default: false,
    description: '',
  });
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [loading, setLoading] = useState(false);
  const [testingAccountId, setTestingAccountId] = useState<string | null>(null);
  const [fetchingAccountId, setFetchingAccountId] = useState<string | null>(null);
  const [clearingAccountId, setClearingAccountId] = useState<string | null>(null);
  const [emailStats, setEmailStats] = useState<Record<string, {
    db_message_count: number;
    total_message_count: number;
    folder_stats: Record<string, number>;
  }>>({});

  // 预设配置
  const presetConfigs = {
    gmail: {
      name: 'Gmail',
      smtp_server: 'smtp.gmail.com',
      smtp_port: 587,
      imap_server: 'imap.gmail.com',
      imap_port: 993,
      use_ssl: true,
    },
    outlook: {
      name: 'Outlook',
      smtp_server: 'smtp.office365.com',
      smtp_port: 587,
      imap_server: 'outlook.office365.com',
      imap_port: 993,
      use_ssl: true,
    },
    qq: {
      name: 'QQ邮箱',
      smtp_server: 'smtp.qq.com',
      smtp_port: 587, // 使用587端口，STARTTLS
      imap_server: 'imap.qq.com',
      imap_port: 993,
      use_ssl: true,
    },
    '163': {
      name: '163邮箱',
      smtp_server: 'smtp.163.com',
      smtp_port: 465,
      imap_server: 'imap.163.com',
      imap_port: 993,
      use_ssl: true,
    },
  };

  // 加载邮箱账号列表
  useEffect(() => {
    loadAccounts();
  }, []);

  const loadAccounts = async () => {
    try {
      setLoading(true);
      const response = await emailAccountsAPI.getAll();
      setAccounts(response.accounts);
      
      // 加载每个账号的邮件统计信息
      const statsPromises = response.accounts.map(async (account) => {
        try {
          const statsResponse = await emailAccountsAPI.getStats(account.id);
          return { accountId: account.id, stats: statsResponse };
        } catch (error) {
          console.error(`Failed to load stats for account ${account.id}:`, error);
          return { accountId: account.id, stats: null };
        }
      });
      
      const statsResults = await Promise.all(statsPromises);
      const newStats: Record<string, any> = {};
      
      statsResults.forEach(({ accountId, stats }) => {
        if (stats) {
          newStats[accountId] = {
            db_message_count: stats.db_message_count,
            total_message_count: stats.total_message_count,
            folder_stats: stats.folder_stats,
          };
        }
      });
      
      setEmailStats(newStats);
    } catch (error) {
      console.error('Failed to load email accounts:', error);
      showMessage('error', '加载失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const showMessage = (type: 'success' | 'error', text: string) => {
    setMessage({ type, text });
    setTimeout(() => setMessage(null), 3000);
  };

  const handleAdd = () => {
    setIsAdding(true);
    setFormData({
      name: '',
      email: '',
      smtp_server: '',
      smtp_port: 587,
      imap_server: '',
      imap_port: 993,
      username: '',
      password: '',
      use_ssl: true,
      is_default: false,
      description: '',
    });
  };

  const handleEdit = (account: EmailAccount) => {
    setEditingId(account.id);
    setFormData({
      name: account.name,
      email: account.email,
      smtp_server: account.smtp_server,
      smtp_port: account.smtp_port,
      imap_server: account.imap_server,
      imap_port: account.imap_port,
      username: account.username,
      password: '', // 不显示密码
      use_ssl: account.use_ssl,
      is_default: account.is_default,
      description: account.description || '',
    });
  };

  const handleCancel = () => {
    setIsAdding(false);
    setEditingId(null);
    setFormData({
      name: '',
      email: '',
      smtp_server: '',
      smtp_port: 587,
      imap_server: '',
      imap_port: 993,
      username: '',
      password: '',
      use_ssl: true,
      is_default: false,
      description: '',
    });
  };

  const handleSave = async () => {
    if (!formData.name.trim() || !formData.email.trim() || !formData.smtp_server.trim() || !formData.imap_server.trim()) {
      showMessage('error', '请填写必要信息');
      return;
    }

    try {
      if (editingId) {
        // 更新
        const updateData: any = { ...formData };
        if (!updateData.password) {
          delete updateData.password; // 如果密码为空，不更新密码
        }
        await emailAccountsAPI.update(editingId, updateData);
        showMessage('success', '邮箱配置更新成功');
      } else {
        // 添加
        await emailAccountsAPI.create(formData);
        showMessage('success', '邮箱配置添加成功');
      }
      
      handleCancel();
      await loadAccounts();
    } catch (error) {
      showMessage('error', error instanceof Error ? error.message : '操作失败');
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('确定要删除这个邮箱配置吗？')) {
      return;
    }

    try {
      await emailAccountsAPI.delete(id);
      await loadAccounts();
      showMessage('success', '邮箱配置删除成功');
    } catch (error) {
      showMessage('error', error instanceof Error ? error.message : '删除失败');
    }
  };

  const handleTestConnection = async (id: string) => {
    try {
      setTestingAccountId(id);
      const response = await emailAccountsAPI.sendTest(id);
      if (response.success) {
        showMessage('success', response.message);
      } else {
        showMessage('error', response.message);
      }
    } catch (error) {
      showMessage('error', error instanceof Error ? error.message : '测试失败');
    } finally {
      setTestingAccountId(null);
    }
  };

  const handleFetchMessages = async (id: string) => {
    try {
      setFetchingAccountId(id);
      const response = await emailAccountsAPI.fetchMessages(id);
      showMessage('success', response.message);
      // 刷新统计信息
      await loadAccountStats(id);
    } catch (error) {
      showMessage('error', error instanceof Error ? error.message : '拉取失败');
    } finally {
      setFetchingAccountId(null);
    }
  };

  const handleClearMessages = async (id: string) => {
    if (!confirm('确定要清空该邮箱账号下的所有邮件吗？此操作不可恢复！')) {
      return;
    }
    
    try {
      setClearingAccountId(id);
      const response = await emailAccountsAPI.clearMessages(id);
      showMessage('success', response.message);
      // 刷新统计信息
      await loadAccountStats(id);
    } catch (error) {
      showMessage('error', error instanceof Error ? error.message : '清空失败');
    } finally {
      setClearingAccountId(null);
    }
  };

  const loadAccountStats = async (accountId: string) => {
    try {
      const statsResponse = await emailAccountsAPI.getStats(accountId);
      setEmailStats(prev => ({
        ...prev,
        [accountId]: {
          db_message_count: statsResponse.db_message_count,
          total_message_count: statsResponse.total_message_count,
          folder_stats: statsResponse.folder_stats,
        }
      }));
    } catch (error) {
      console.error(`Failed to load stats for account ${accountId}:`, error);
    }
  };

  const handlePresetSelect = (preset: string) => {
    const config = presetConfigs[preset as keyof typeof presetConfigs];
    if (config) {
      setFormData(prev => ({
        ...prev,
        ...config,
        name: prev.name || config.name,
      }));
    }
  };

  const handleExport = async () => {
    try {
      const data = JSON.stringify(accounts.map(account => ({
        name: account.name,
        email: account.email,
        smtp_server: account.smtp_server,
        smtp_port: account.smtp_port,
        imap_server: account.imap_server,
        imap_port: account.imap_port,
        username: account.username,
        use_ssl: account.use_ssl,
        description: account.description,
      })), null, 2);
      const blob = new Blob([data], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `feng-admin-email-accounts-${new Date().toISOString().split('T')[0]}.json`;
      a.click();
      URL.revokeObjectURL(url);
      showMessage('success', '导出成功');
    } catch (error) {
      console.error('Export failed:', error);
      showMessage('error', '导出失败');
    }
  };

  const handleImport = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'application/json';
    input.onchange = async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) return;

      try {
        const text = await file.text();
        const importedAccounts = JSON.parse(text);
        
        if (!Array.isArray(importedAccounts)) {
          throw new Error('数据格式错误');
        }

        // 逐个导入邮箱配置
        for (const account of importedAccounts) {
          try {
            await emailAccountsAPI.create({
              ...account,
              password: 'imported-password-placeholder', // 导入时需要重新设置密码
            });
          } catch (err) {
            console.error('Failed to import account:', account.name, err);
          }
        }
        
        await loadAccounts();
        showMessage('success', '导入成功');
      } catch (error) {
        showMessage('error', error instanceof Error ? error.message : '导入失败');
      }
    };
    input.click();
  };

  return (
    <div className="space-y-6">
      {/* Page header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">邮箱管理</h1>
          <p className="text-muted-foreground">管理你的邮箱账号配置，支持收发邮件</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={handleExport}>
            <Download className="mr-2 h-4 w-4" />
            导出
          </Button>
          <Button variant="outline" size="sm" onClick={handleImport}>
            <Upload className="mr-2 h-4 w-4" />
            导入
          </Button>
          <Button onClick={handleAdd}>
            <Plus className="mr-2 h-4 w-4" />
            添加邮箱
          </Button>
        </div>
      </div>

      {/* Message */}
      {message && (
        <Alert className={message.type === 'error' ? 'border-destructive' : 'border-green-500'}>
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>{message.text}</AlertDescription>
        </Alert>
      )}

      {/* Add/Edit Dialog */}
      <Dialog open={isAdding || !!editingId} onOpenChange={handleCancel}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editingId ? '编辑邮箱配置' : '添加新邮箱'}</DialogTitle>
            <DialogDescription>配置邮箱的SMTP和IMAP设置</DialogDescription>
          </DialogHeader>
          
          <div className="space-y-6">
            {/* 预设配置选择 */}
            <div className="space-y-2">
              <Label>快速配置</Label>
              <Select onValueChange={handlePresetSelect}>
                <SelectTrigger>
                  <SelectValue placeholder="选择预设配置" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="gmail">Gmail</SelectItem>
                  <SelectItem value="outlook">Outlook</SelectItem>
                  <SelectItem value="qq">QQ邮箱</SelectItem>
                  <SelectItem value="163">163邮箱</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <Tabs defaultValue="basic" className="w-full">
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="basic">基本配置</TabsTrigger>
                <TabsTrigger value="advanced">高级配置</TabsTrigger>
              </TabsList>
              
              <TabsContent value="basic" className="space-y-4">
                <div className="grid gap-4">
                  <div className="grid gap-2">
                    <Label htmlFor="name">显示名称 *</Label>
                    <Input
                      id="name"
                      placeholder="例如：我的Gmail"
                      value={formData.name}
                      onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    />
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="email">邮箱地址 *</Label>
                    <Input
                      id="email"
                      type="email"
                      placeholder="例如：user@gmail.com"
                      value={formData.email}
                      onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    />
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="username">用户名 *</Label>
                    <Input
                      id="username"
                      placeholder="通常是邮箱地址"
                      value={formData.username}
                      onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                    />
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="password">密码/授权码 *</Label>
                    <Input
                      id="password"
                      type="password"
                      placeholder="邮箱密码或应用专用密码"
                      value={formData.password}
                      onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                    />
                  </div>
                </div>
              </TabsContent>
              
              <TabsContent value="advanced" className="space-y-4">
                <div className="grid gap-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="grid gap-2">
                      <Label htmlFor="smtp_server">SMTP服务器 *</Label>
                      <Input
                        id="smtp_server"
                        placeholder="smtp.gmail.com"
                        value={formData.smtp_server}
                        onChange={(e) => setFormData({ ...formData, smtp_server: e.target.value })}
                      />
                    </div>
                    <div className="grid gap-2">
                      <Label htmlFor="smtp_port">SMTP端口 *</Label>
                      <Input
                        id="smtp_port"
                        type="number"
                        placeholder="587"
                        value={formData.smtp_port}
                        onChange={(e) => setFormData({ ...formData, smtp_port: parseInt(e.target.value) || 587 })}
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="grid gap-2">
                      <Label htmlFor="imap_server">IMAP服务器 *</Label>
                      <Input
                        id="imap_server"
                        placeholder="imap.gmail.com"
                        value={formData.imap_server}
                        onChange={(e) => setFormData({ ...formData, imap_server: e.target.value })}
                      />
                    </div>
                    <div className="grid gap-2">
                      <Label htmlFor="imap_port">IMAP端口 *</Label>
                      <Input
                        id="imap_port"
                        type="number"
                        placeholder="993"
                        value={formData.imap_port}
                        onChange={(e) => setFormData({ ...formData, imap_port: parseInt(e.target.value) || 993 })}
                      />
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Switch
                      id="use_ssl"
                      checked={formData.use_ssl}
                      onCheckedChange={(checked) => setFormData({ ...formData, use_ssl: checked })}
                    />
                    <Label htmlFor="use_ssl">使用SSL/TLS</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Switch
                      id="is_default"
                      checked={formData.is_default}
                      onCheckedChange={(checked) => setFormData({ ...formData, is_default: checked })}
                    />
                    <Label htmlFor="is_default">设为默认邮箱</Label>
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="description">描述</Label>
                    <Input
                      id="description"
                      placeholder="可选描述"
                      value={formData.description}
                      onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                    />
                  </div>
                </div>
              </TabsContent>
            </Tabs>
            
            <div className="flex gap-2">
              <Button onClick={handleSave}>
                <Check className="mr-2 h-4 w-4" />
                保存
              </Button>
              <Button variant="outline" onClick={handleCancel}>
                取消
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Accounts List */}
      {loading && accounts.length === 0 ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
        </div>
      ) : accounts.length === 0 && !isAdding ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <Mail className="h-12 w-12 text-muted-foreground" />
            <p className="mt-4 text-lg font-medium">还没有邮箱配置</p>
            <p className="text-sm text-muted-foreground">点击"添加邮箱"按钮创建你的第一个邮箱配置</p>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {accounts.map((account) => (
            <Card key={account.id} className="relative">
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-2">
                    <Mail className="h-5 w-5 text-primary" />
                    <CardTitle className="text-lg">{account.name}</CardTitle>
                  </div>
                  <div className="flex gap-1">
                    {account.is_default && (
                      <Badge variant="secondary">默认</Badge>
                    )}
                    <Badge variant="outline">邮箱</Badge>
                    {account.is_first_fetch ? (
                      <Badge variant="destructive" className="text-xs">
                        <AlertCircle className="mr-1 h-3 w-3" />
                        未全量拉取
                      </Badge>
                    ) : (
                      <Badge variant="default" className="text-xs bg-green-100 text-green-800 border-green-200">
                        <Check className="mr-1 h-3 w-3" />
                        已全量拉取
                      </Badge>
                    )}
                  </div>
                </div>
                <CardDescription>{account.email}</CardDescription>
                {account.description && (
                  <CardDescription className="text-xs">{account.description}</CardDescription>
                )}
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                    <div className="text-sm text-muted-foreground">
                      <div>SMTP: {account.smtp_server}:{account.smtp_port}</div>
                      <div>IMAP: {account.imap_server}:{account.imap_port}</div>
                      <div>SSL: {account.use_ssl ? '是' : '否'}</div>
                      <div className="flex items-center gap-1 mt-2">
                        {account.is_first_fetch ? (
                          <>
                            <AlertCircle className="h-4 w-4 text-orange-500" />
                            <span className="text-orange-600">需要全量拉取邮件</span>
                          </>
                        ) : (
                          <>
                            <Check className="h-4 w-4 text-green-500" />
                            <span className="text-green-600">已完成全量拉取</span>
                          </>
                        )}
                      </div>
                      {account.last_fetch_at && (
                        <div className="text-xs text-muted-foreground mt-1">
                          上次拉取: {new Date(account.last_fetch_at).toLocaleString()}
                        </div>
                      )}
                      {/* 邮件统计信息 */}
                      {emailStats[account.id] && (
                        <div className="mt-2 p-2 bg-gray-50 rounded-md">
                          <div className="text-xs font-medium text-gray-700 mb-1">邮件统计</div>
                          <div className="text-xs text-gray-600">
                            <div>数据库: {emailStats[account.id].db_message_count} 封</div>
                            <div>邮箱总计: {emailStats[account.id].total_message_count} 封</div>
                            {Object.keys(emailStats[account.id].folder_stats).length > 0 && (
                              <div className="mt-1">
                                {Object.entries(emailStats[account.id].folder_stats).map(([folder, count]) => (
                                  <div key={folder} className="text-xs">
                                    {folder}: {count} 封
                                  </div>
                                ))}
                              </div>
                            )}
                          </div>
                        </div>
                      )}
                    </div>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1"
                      onClick={() => handleTestConnection(account.id)}
                      disabled={testingAccountId === account.id}
                    >
                      {testingAccountId === account.id ? (
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      ) : (
                        <Send className="mr-2 h-4 w-4" />
                      )}
                      测试
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1"
                      onClick={() => handleFetchMessages(account.id)}
                      disabled={fetchingAccountId === account.id}
                    >
                      {fetchingAccountId === account.id ? (
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      ) : (
                        <RefreshCw className="mr-2 h-4 w-4" />
                      )}
                      拉取
                    </Button>
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1"
                      onClick={() => handleClearMessages(account.id)}
                      disabled={clearingAccountId === account.id}
                    >
                      {clearingAccountId === account.id ? (
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      ) : (
                        <Trash2 className="mr-2 h-4 w-4" />
                      )}
                      清空
                    </Button>
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1"
                      onClick={() => handleEdit(account)}
                    >
                      <Edit2 className="mr-2 h-4 w-4" />
                      编辑
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1"
                      onClick={() => handleDelete(account.id)}
                    >
                      <Trash2 className="mr-2 h-4 w-4" />
                      删除
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
